﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

/// <summary>
/// Handles spawning of enemies, setup consist of two objects the actual start point and a rally point.  
/// The first is hidden behind a wall while the second is actually in the level, enemy is not activated
/// until it reaches the rally point - this looks a lot nicer than enemies popping into existence.
/// References global WaveMan object to get what Enemy type to spawn.
/// </summary>

public class EnemySpawn : MonoBehaviour {

  //  public List<GameObject> SpawnFabs ;
    public float SpawnRate = 2;
    public Transform SpawnTarget;
    float SpawnTimer;

    List<Ai> Spawning = new List<Ai>();

    Transform Trnsfrm;
    WaveMan WMan;

    void Awake() {

        SpawnTimer = SpawnRate;
        Trnsfrm = transform;
        WMan = FindObjectOfType<WaveMan>();
    }
    void Start() {

        WMan.registerSpawner( SpawnRate );
    }

    void Update () {

        if((SpawnTimer -= Time.deltaTime) < 0.0f) {

            //if( Physics2D.CircleCast(....   - todo check are is clear

            SpawnTimer += SpawnRate;

            var fab = WMan.getSpawn( ref SpawnTimer, SpawnRate );
            if( fab != null ) {
                var bot = (Instantiate(fab, Trnsfrm.position, Quaternion.identity) as GameObject).GetComponent<Ai>();
                Spawning.Add( bot );
                bot.enabled = false;
                bot.rigidbody2D.isKinematic = true;
            }
           // Destroy(this);
        }

        for( int i = Spawning.Count; i-- != 0; ) {
            Ai bot = Spawning[i];

            if(!bot) {
                Spawning.RemoveAt(i);
                continue;
            }
            Vector2 vec = SpawnTarget.position - bot.transform.position;

            Debug.DrawLine(bot.transform.position +(Vector3) vec, bot.transform.position, Color.red);
            float dis = vec.magnitude, delta = Time.deltaTime * bot.speed*2.0f;

            if(delta > dis) {
                bot.enabled = true;
                bot.rigidbody2D.isKinematic = false;
                Spawning.RemoveAt(i);
            } else {
                vec.Normalize();
                bot.transform.position += (Vector3) ( vec * (delta ));
             //   bot.rigidbody2D.velocity = vec;
            }
        }
	}
}
